<template>
  <div class="generate-qrcode">
    <!-- 头部 -->
    <div class="app-main-content-box">
      <div class="flexRBC">
        <el-form
          :model="formData"
          ref="ruleForm"
          label-width="80px"
          :rules="rules"
        >
          <el-form-item label="公告标题" prop="title">
            <el-input
              v-model="formData.title"
              size="medium"
              placeholder="请输入标题"
              maxlength="10"
              show-word-limit
              :disabled="onlyRead"
            ></el-input>
          </el-form-item>
          <el-form-item label="公告简介" prop="introduction">
            <el-input
              v-model="formData.introduction"
              placeholder="请输入公告简介"
              maxlength="30"
              type="textarea"
              show-word-limit
              :disabled="onlyRead"
            ></el-input>
          </el-form-item>
          <el-form-item label="公告内容">
            <WangEditor
              @editData="editData"
              :editValue="formData.context"
              :isDisable="routerPar.type == 'read' ? true : false"
            />
          </el-form-item>
          <el-form-item label="可见群体" prop="showType">
            <el-radio-group v-model="formData.showType" :disabled="onlyRead">
              <el-radio :label="1">全部用户</el-radio>
              <el-radio :label="2">会员卡</el-radio>
              <el-radio :label="3">会员标签</el-radio>
            </el-radio-group>
            <div v-if="formData.showType == 2 || formData.showType == 3">
              <div v-if="formData.showType == 2">
                <el-checkbox-group v-model="checkList" style="max-width: 300px">
                  <el-checkbox
                    :disabled="onlyRead"
                    :label="item.id"
                    v-for="(item, index) in cardList"
                    :key="index"
                    >{{ item.categoryName }}</el-checkbox
                  >
                </el-checkbox-group>
              </div>
              <div v-if="formData.showType == 3">
                <el-button @click="openVipDialog"
                  >已选{{ tagGroupList.length }}个标签</el-button
                >
              </div>
            </div>
          </el-form-item>
          <el-form-item label="显示时间" prop="date">
            <el-date-picker
              :disabled="onlyRead"
              v-model="formData.date"
              align="right"
              size="medium"
              type="datetimerange"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              :default-time="['00:00:00', '23:59:59']"
              value-format="yyyy-MM-dd HH:mm:ss"
              :picker-options="expireTimeOption"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="序号" prop="orderNum">
            <el-input
              v-model="formData.orderNum"
              size="medium"
              placeholder="请输入序号"
              :disabled="onlyRead"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="medium" @click="$router.back()"
              >取消</el-button
            >
            <el-button
              :disabled="onlyRead"
              type="primary"
              size="medium"
              @click="submitForm('ruleForm')"
              >保存</el-button
            >
          </el-form-item>
        </el-form>

        <el-dialog title="会员标签" :visible.sync="showTree" width="30%">
          <el-tree
            :data="tagList"
            show-checkbox
            node-key="id"
            default-expand-all
            :props="defaultProps"
            ref="tree"
          >
          </el-tree>
          <span slot="footer" class="dialog-footer">
            <el-button @click="showTree = false">取消</el-button>
            <el-button type="primary" @click="closeTree()">确定</el-button>
          </span>
        </el-dialog>
      </div>
    </div>
  </div>
</template>ß

<script>
import { getTagsList } from "@/api/vip";
import {
  getVipCardList,
  addAndEditAffiche,
  getAfficheDetail,
} from "@/api/business";

import WangEditor from "@/components/WangEditor";
export default {
  components: {
    WangEditor,
  },
  data() {
    var orderNumRule = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("序号不能为空"));
      } else if (Number.isNaN(parseInt(value))) {
        return callback(new Error("序号只支持数字输入"));
      } else if (value <= 0 || value > 999) {
        return callback(new Error("序号范围在1~999"));
      } else if (value.toString().indexOf(".") != -1) {
        return callback(new Error("序号不可为小数"));
      } else {
        callback();
      }
    };
    return {
      // 表单数据
      formData: {
        title: "",
        introduction: "",
        showType: 1,
        date: [],
        orderNum: "",
        context: "",
        orderNum: 1,
        // 会员标签列表
        configIdList: [],
        content: "",
      },
      // 上级页面参数
      routerPar: {},
      //
      cardList: [],
      checkList: [],
      tagGroupList: [],
      tagList: [],
      defaultProps: {
        children: "tags",
        label: "tagName",
        disabled: this.isdisabledFn,
      },
      showTree: false,
      rules: {
        title: [
          { required: true, message: "请输入公告标题", trigger: "blur" },
          { min: 1, max: 10, message: "长度在1到10个字符", trigger: "blur" },
        ],
        showType: [
          { required: true, message: "请选择活动区域", trigger: "change" },
        ],
        introduction: [
          { required: true, message: "请输入公告简介", trigger: "change" },
        ],
        date: [
          {
            type: "array",
            required: true,
            message: "请选择开始时间和结束时间",
            trigger: "change",
          },
        ],
        orderNum: [
          { validator: orderNumRule, trigger: "change", type: "number" },
        ],
      },
      onlyRead: false,
      //设置失效日期今天之前的日期不可选
      expireTimeOption: {
        disabledDate(date) {
          //disabledDate 文档上：设置禁用状态，参数为当前日期，要求返回 Boolean
          return date.getTime() < Date.now() - 24 * 60 * 60 * 1000;
        },
      },
    };
  },
  mounted() {
    this.routerPar = this.$route.query;
    this.initData();
  },
  methods: {
    isdisabledFn() {
      return this.onlyRead;
    },
    editData(data) {
      let defaultVal = "<p><br></p>";
      // if (data != defaultVal) {
      this.formData.context = data;
      // }
    },
    openVipDialog() {
      this.showTree = true;
      this.$nextTick(() => {
        if (this.tagGroupList.length > 0) {
          this.$refs.tree.setCheckedNodes(this.tagGroupList);
        }
      });
    },
    handleClose() {},
    // 关闭会员标签弹窗
    closeTree() {
      let checkList = this.$refs.tree.getCheckedNodes();
      checkList.forEach((item, index) => {
        if (Object.keys(item).indexOf("tags") != -1) {
          checkList.splice(index, 1);
        }
      });
      if (checkList.length <= 0) {
        this.$message.error("至少要选择一条会员标签数据");
        return;
      }
      this.tagGroupList = checkList;
      this.$refs.tree.setCheckedKeys([]);
      this.showTree = false;
    },
    // 提交数据
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let {
            formData: { showType, date, context },
            checkList,
            tagGroupList,
            formData,
            routerPar,
          } = this;
          let defaultVal = "<p><br></p>";
          let configIdList = [];
          if (context == defaultVal) {
            this.$message.error("公告内容不能为空");
            return;
          }
          if (showType == 2) {
            if (checkList.length <= 0) {
              this.$message.error("会员卡至少要勾选一条数据");
              return;
            } else {
              configIdList = checkList;
            }
          } else if (showType == 3) {
            if (tagGroupList.length <= 0) {
              this.$message.error("请选择会员标签再进行操作");
              return;
            } else {
              tagGroupList.forEach((item) => {
                configIdList.push(item.id);
              });
            }
          }
          formData.configIdList = configIdList;
          formData.showEndTime = this.forMartDate(date[1]);
          formData.showStartTime = this.forMartDate(date[0]);
          delete formData.date;
          addAndEditAffiche(formData).then((res) => {
            if (res.code == 0) {
              this.$message.success(
                `${routerPar == "add" ? "新增公告成功" : "编辑公告成功"}`
              );
              this.resetPage();
            }
          });
        }
      });
    },
    // 重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    // 格式化时间
    forMartDate(date) {
      let newDate = date.split("");
      newDate.splice(newDate.length - 3, 3);
      return newDate.join("");
    },
    // 重置页面相关参数
    resetPage() {
      this.formData = {
        title: "",
        introduction: "",
        showType: 1,
        date: [],
        orderNum: "",
        context: "",
        orderNum: 1,
        // 会员标签列表
        configIdList: [],
      };
      this.resetForm("ruleForm");
      this.$router.back();
    },
    // 初始化数据
    initData() {
      let { routerPar } = this;
      getVipCardList()
        .then((res) => {
          this.cardList = res.data;
        })
        .finally(() => {
          this.loading = false;
        });
      getTagsList().then((res) => {
        if (res.code == 0) {
          res.data.forEach((e) => {
            (e.id = e.groupId), (e.tagName = e.tagGroup);
          });
          this.tagList = res.data;
        }
      });
      if (routerPar.type == "edit" || routerPar.type == "read") {
        if (routerPar.type == "read") {
          this.onlyRead = true;
        }
        getAfficheDetail({ id: routerPar.id }).then((res) => {
          if (res.code == 0) {
            let {
              data: { showEndTime, showStartTime },
              data,
            } = res;
            data.date = [];
            data.date[1] = `${showEndTime}:59`;
            data.date[0] = `${showStartTime}:00`;
            if (data.showType == 2) {
              let dataStrArr = data.configIds.split(","); //分割成字符串数组
              this.checkList = dataStrArr.map((item) => {
                return +item;
              });
            }
            this.formData = data;
            this.tagGroupList = data.tagsDetail || [];
          }
        });
      }
    },
  },
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
// .generate-qrcode {
//   .content {
//     margin-top: 10px;
//   }
//   /* 搜索*/
//   .list-search {
//     .el-input {
//       width: 40%;
//       min-width: 300px;
//       max-width: 500px;
//       margin-right: 10px;
//     }
//   }
//   /* 筛选 */
//   .el-radio + .el-radio {
//     margin-left: 0;
//   }
//   .el-radio {
//     margin-right: 10px;
//     height: 32px;
//     line-height: 32px;
//   }
// }
</style>
